<template>
    <div class="player" @mousedown="downPlayer" ref="main" @contextmenu="smallView">

        <!-- 播放器 -->
        <audio ref="player" src='' @timeupdate="updateProgressBar" @volumechange="volumechange" @play="playerPlay"
            @pause="playerPause" @ended="ended" preload="none"></audio>

        <!-- 信息 -->
        <div ref="info" class="info">

            <!-- 音乐名 -->
            <div ref="title" class="title">{{ title }} - {{ author }}</div>

            <!-- 歌词 -->
            <div class="lyrics">
                <ul ref="lyric" v-if="musicList.length != 0">
                    <li v-for="(lyric, index) in musicList[this.playingMusic].lyrics" :key="index">
                        {{ lyric }}
                    </li>
                </ul>
            </div>

            <!-- 进度条 -->
            <div class="state">
                <!-- 当前播放进度 -->
                <span>{{ currentTime }}</span>
                <!-- 可拖动进度条 -->
                <input type="range" min="0" max="100" :value="progress != progress ? 0 : progress" class="musicRange"
                    @input="updateProgress" @mousedown="mousedown" @mouseup="mouseup" ref="progress">
                <!-- 总进度 -->
                <span>{{ duration }}</span>
            </div>

        </div>

        <!-- 控制台 -->
        <div class="console" ref="console">

            <div class="control">

                <!-- 音量控制 -->
                <div ref="posters" class="posters" @mousedown="mousedownVolume">
                    <!-- 旋转海报 -->
                    <img :src=img alt="">
                </div>

                <!-- 控制按钮 -->
                <div class="operation">
                    <!-- 上一首 -->
                    <button @click="last"></button>
                    <!-- 播放/暂停 -->
                    <button @click="p_s" ref="p_s"></button>
                    <!-- 下一首 -->
                    <button @click="next"></button>
                    <!-- 曲库 -->
                    <button @click="library"></button>
                </div>

            </div>

            <!-- 曲库 -->
            <div class="library" ref="library">
                <ul>

                    <!-- 添加音乐 -->
                    <li style="color: rgb(255 146 50); text-align: center; flex-direction: column" @click="addMusic">
                        <span style="font-size: large;">添加音乐</span>
                        <br style="display: none;">
                        (音乐查询api来自myfreemp3.sharerj.com)
                        <br>
                        (音乐解析api来自apis.jxcxin.cn)
                    </li>

                    <!-- 音乐列表 -->
                    <div v-if="musicList.length != 0" ref="music">
                        <li v-for="(music, index) in musicList" :key=index @click="checkPlay(index)">
                            {{ music.title + '-' + music.author }}
                            <button class="deleteMusic" @click="deleteMusic(index)">删除</button>
                        </li>
                    </div>

                    <!-- 版权 -->
                    <li>&copy; 2023 Limerence. All Rights Reserved.</li>

                </ul>
            </div>
        </div>

        <!-- 缩略视图 -->
        <div class="smallView" ref="smallView" @click="p_s">
            <img :src=img alt="">
        </div>

    </div>
</template>

<style lang="scss" scoped>
// 播放器样式
.player {
    width: 500rem;
    height: 240rem;
    //background-color: antiquewhite;
    margin: auto;
    position: absolute;
    left: calc(50% - 250rem);
    //禁止选中、拖动、防止调整音量时发生冲突
    /* 禁止选中 */
    user-select: none;
    /* Safari */
    //-webkit-user-select: none;
    /* 禁用webkit浏览器的拖动影子 */
    //-webkit-user-drag: none;

    // 信息
    .info {
        width: 90%;
        height: 110rem;
        margin: auto;
        background: linear-gradient(90deg, rgba(246, 246, 246, 1) 0%, rgba(255, 189, 251, 0.15) 35%, rgba(0, 212, 255, 1) 100%);
        border-radius: 15rem 15rem 0 0;
        position: relative;
        z-index: 0;
        opacity: 0;

        transition: 0.5s;
        padding: 5rem 10rem;

        //--textWidth: 0;

        // 音乐标题名
        .title {
            position: relative;
            width: 90%;
            height: 25rem;
            //background-color: aqua;
            margin: auto;
            text-align: center;
            font-family: 'Fangsong', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
            font-size: 25rem;
            white-space: nowrap;
            overflow: hidden;
            animation: showTitle 20s linear infinite;
        }

        // 标题左右滚动动画
        @keyframes showTitle {
            0% {
                text-indent: 50%;
            }

            50% {
                text-indent: -50%;
            }

            100% {
                text-indent: 50%;
            }
        }

        // 歌词
        .lyrics {
            height: 40rem;
            overflow: hidden;

            ul {
                position: relative;
                list-style: none;
                margin: 0;
                padding: 2rem 0;
                transition: top 1s;

                li {
                    font-family: 'Courier New', Courier, monospace;
                    font-size: 18rem;
                    height: 40rem;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    text-align: center;
                }
            }
        }

        // 状态（进度条区域）
        .state {
            height: 50rem;
            display: flex;
            align-items: center;
            padding-left: 20%;

            span{
                font-size: small;
            }

            // 混合，保证兼容
            @mixin appearance($value) {
                -webkit-appearance: $value;
                -moz-appearance: $value;
                -ms-appearance: $value;
                appearance: $value;
            }

            // 进度条
            .musicRange {
                // 取消默认样式
                @include appearance(none);
                width: 70%;
                height: 20rem;
                margin: auto;
                border-radius: 10rem;
                background: none;
                //background: -webkit-linear-gradient(#059CFA, #059CFA) no-repeat;
                //background-size: 0% 100%;

                // 滑块
                &::-webkit-slider-thumb {
                    @include appearance(none);
                    appearance: none;
                    width: 20rem;
                    height: 20rem;
                    border-radius: 50%;
                    background: #ffffff;
                    border: 1rem solid transparent;
                    border-image: linear-gradient(#f44336, #f44336) 0 fill / 8rem 20rem 8rem 0/ 0 0 0 500rem;
                    margin-top: -8rem;
                }

                // 轨道
                &::-webkit-slider-runnable-track {
                    height: 4rem;
                    background: #eee;
                }

                &::-webkit-slider-container {
                    height: 20rem;
                    overflow: hidden;
                }

                // 取消焦点事件的外框
                &:focus {
                    outline: none;
                }
            }

        }

    }

    // 显示信息区域的动画
    @keyframes showInfo {
        from {
            transform: translateY(100rem);
        }

        to {
            transform: translateY(0rem);
        }
    }

    // 隐藏信息区域的动画
    @keyframes hiddenInfo {
        from {
            transform: translateY(0rem);
        }

        to {
            transform: translateY(100rem);
        }
    }

    // 显示信息区域的样式
    .showInfo {
        animation: showInfo 1s forwards;
        opacity: 1;
    }

    // 隐藏信息区域的样式
    .hiddenInfo {
        animation: hiddenInfo 1s forwards;
        opacity: 0;
    }

    // 控制区域
    .console {
        background-color: white;
        border-radius: 15rem;
        position: relative;
        z-index: 1;

        // 控制
        .control {
            width: 100%;
            height: 120rem;

            // 海报区域
            .posters {
                height: 110rem;
                width: 110rem;
                border-radius: 50%;
                border: solid white 5rem;
                position: relative;
                //margin: 0 20rem;
                bottom: 30rem;
                display: inline-block;
                overflow: hidden;

                --volumeHeight: 100%;

                // 音量样式
                &::after {
                    content: '';
                    display: block;
                    width: 100%;
                    height: var(--volumeHeight);
                    background: linear-gradient(0deg, rgba(34, 193, 195, 1) 0%, rgba(253, 187, 45, 1) 100%);
                    position: absolute;
                    bottom: 0;
                    opacity: 0;
                    transition: opacity 0.5s;
                }

                &:hover {
                    &::after {
                        opacity: 0.8;
                    }
                }

                // 海报
                img {
                    width: 100%;
                    height: 100%;
                    /* 禁止选中 */
                    user-select: none;
                    /* Safari */
                    -webkit-user-select: none;
                    /* 禁用鼠标事件 */
                    pointer-events: none;
                    /* 禁用webkit浏览器的拖动影子 */
                    -webkit-user-drag: none;
                }
            }

            // 操作
            .operation {
                height: 100%;
                width: calc(100% - 120rem);
                display: inline-flex;
                justify-content: space-evenly;
                align-items: center;
                position: relative;
                vertical-align: top;

                // 正在播放样式
                .isPlaying {
                    background: url('@/assets/player/Player, pause.png') no-repeat !important;
                    background-size: cover !important;
                }

                // 按钮
                button {
                    width: 50rem;
                    height: 50rem;
                    border: none;
                    border-radius: 5rem;
                    transition: background-color 0.5s;

                    &:nth-child(1) {
                        background: url('@/assets/player/Player, last.png') no-repeat;
                        background-size: cover;
                    }

                    &:nth-child(2) {
                        background: url('@/assets/player/Player, play.png') no-repeat;
                        background-size: cover;
                    }

                    &:nth-child(3) {
                        background: url('@/assets/player/Player, next.png') no-repeat;
                        background-size: cover;
                    }

                    &:nth-child(4) {
                        background: url('@/assets/player/player-list-play.png') no-repeat;
                        background-size: cover;
                    }

                    &:hover {
                        background-color: rgb(206, 206, 206) !important;
                    }
                }
            }
        }

        //区库
        .library {
            height: 0;
            background: linear-gradient(-90deg, rgb(246, 246, 196) 0%, rgba(255, 189, 251, 0.3) 65%, rgb(0, 212, 255, 0.5) 100%);
            //display: none;
            border-radius: 0 0 10rem 10rem;
            overflow: hidden;
            transition: height 0.5s, opacity 0.5s;
            opacity: 0;

            ul {
                height: 280rem;
                width: 100%;
                list-style: none;
                margin: 0;
                padding: 10rem 8rem;
                overflow: auto;

                li {
                    height: 56rem;
                    display: flex;
                    align-items: center;
                    transition: all 0.5s;
                    font-family: 'Courier New', Courier, monospace;
                    justify-content: center;
                    position: relative;
                    font-size: small;

                    &:hover {
                        background-color: rgb(255, 255, 255, 0.6);
                    }

                    &:hover button {
                        display: block;
                    }

                }

                // 删除音乐按钮
                .deleteMusic {
                    height: 40rem;
                    width: 60rem;
                    position: absolute;
                    right: 8rem;
                    background-color: rgb(255, 255, 255, 0.1);
                    border: none;
                    display: none;
                    transition: all 0.5s;

                    &:hover {
                        background-color: #e0948f;
                    }
                }
            }
        }
    }

    // 360度旋转动画
    @keyframes rotateImg {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }

    // 旋转的样式（播放后将此样式加到需要旋转的海报图片上）
    .rotateImg {
        animation: rotateImg 5s linear infinite;
    }

    // 缩略视图样式
    .smallView {
        width: 100rem;
        height: 100rem;
        display: none;
        position: absolute;
        bottom: 0px;
        border-radius: 50%;
        border: 5px solid white;
        overflow: hidden;

        &::after {
            content: '';
            display: block;
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            background: url('@/assets/player/Player, play.png') no-repeat;
            background-size: cover;
            transform: scale(0.5);
            opacity: 0;
            transition: opacity 0.5s;
        }

        &:hover {
            &::after {
                opacity: 1;
            }
        }

        img {
            width: 100%;
            height: 100%;
        }
    }

    // 缩略视图正在播放（暂停图背景）
    .sviewIsPlaying {
        &::after {
            background: url('@/assets/player/Player, pause.png') no-repeat !important;
            background-size: cover !important;
        }
    }

}
</style>

<script>

export default {

    data() {
        return {
            // 是否在播放（默认：否）
            isPlaying: false,
            //是否在加载（默认：否）
            isLoading: false,
            // 曲库（默认：空，自动本地加载）
            musicList: [],
            // 当前所播放的曲库列表下标
            playingMusic: 0,
            // 播放进度（%）
            progress: 0,
            // 当前音乐播放时长
            currentTime: '00:00',
            // 总音乐时长
            duration: '00:00',
            // 音量大小（0-1）
            volume: 0,
            // 鼠标按下位置
            pos: {
                x: 0,
                y: 0
            },
            // div累加偏移量
            addPos: {
                left: 0,
                top: 0,
            },
        }
    },
    computed: {
        // 默认值
        // 默认为'',将由js获取处理后直接赋予缓存Blob，故不再计算url
        // url() {
        //     return this.musicList.length > 0 ? this.musicList[this.playingMusic]?.url : '';
        // },
        title() {
            return this.musicList.length > 0 ? this.musicList[this.playingMusic]?.title : 'Limerence音乐播放器-侵权请联系';
        },
        author() {
            return this.musicList.length > 0 ? this.musicList[this.playingMusic]?.author : '';
        },
        lyrics() {
            return this.musicList.length > 0 ? this.musicList[this.playingMusic]?.lrc : '';
        },
        img() {
            return this.musicList.length > 0 ? this.musicList[this.playingMusic]?.pic : require('@/assets/player/music.png');
        },
    },
    created() {
        //
    },
    mounted() {
        //加载本地歌曲列表
        const musicList = JSON.parse(localStorage.getItem("musicList"));
        if (musicList != null) {
            this.musicList = musicList;
            console.log("加载本地曲库", musicList);
        }

        //计算主界面的左偏初始值，校对移动偏移
        this.addPos.left = parseInt(getComputedStyle(this.$refs.main).left);
    },
    methods: {
        // 缩略视图
        smallView(e) {
            e.preventDefault();
            this.$refs.info.style.display = this.$refs.info.style.display == 'none' ? 'block' : 'none';
            this.$refs.console.style.display = this.$refs.console.style.display == 'none' ? 'block' : 'none';
            let smallView = this.$refs.smallView;
            if (smallView.style.display == 'block') {
                smallView.style.display = 'none';
            } else {
                smallView.style.display = 'block';
            }

        },

        // 错误监听
        audioErr() {
            if (this.musicList.length > 0) {
                alert("加载出错了，请检查网络");
            }
        },

        // 以下三个播放器监听事件 用于 拖拽播放器位置
        // 播放器鼠标按下监听
        downPlayer(e) {
            //e.preventDefault();
            //防止与音量调节发生冲突
            if (e.target == this.$refs.posters) {
                return;
            //防止与进度调节发生冲突
            } else if (e.target == this.$refs.progress) {
                return;
            } else {
                this.pos = {
                    x: e.clientX,
                    y: e.clientY,
                };
                //console.log("按下，此时按下的位置", this.pos.x, this.pos.y);
            }
            document.addEventListener('mousemove', this.drag);
            document.addEventListener('mouseup', this.upPlayer);
        },
        // 播放器鼠标移动监听
        drag(e) {
            e.preventDefault();
            //console.log("addpos的值", this.addPos.left, this.addPos.top);
            //console.log(parseInt(getComputedStyle(this.$refs.main).left));
            
            const left = this.addPos.left + e.clientX - this.pos.x;
            const right = window.innerWidth - this.$refs.main.clientWidth;
            if (left > 0 && left <= right) {
                this.$refs.main.style.left = left + 'px';
            } else {
                // 感觉上不用写，结果测试发现当移动太快超出范围时,监听器触发并不及时导致上述
                //判断达不到边界值，故作此优化，下同理
                this.$refs.main.style.left = left <= 0 ? '0px' : right + 'px';
            }
            const top = this.addPos.top + e.clientY - this.pos.y;
            const bottom = window.innerHeight - this.$refs.main.clientHeight
            if (top > 0 && top <= bottom) {
                this.$refs.main.style.top = top + 'px';
            } else {
                // 同上
                this.$refs.main.style.top = top <= 0 ? '0px' : bottom + 'px';
            }
            //console.log("移动，此时左右是", this.$refs.main.style.left, "---", this.$refs.main.style.top);
        },
        // 播放器鼠标松开监听
        upPlayer(e) {
            e.preventDefault();
            // 注意使用默认值（|| 默认值）不然第一次执行可能会出现NaN，导致数据运行直接出错
            this.addPos.left = parseInt(this.$refs.main.style.left || this.addPos.left);
            this.addPos.top = parseInt(this.$refs.main.style.top || 0);
            //console.log("记录偏移", this.addPos.left, this.addPos.top);
            // 移除鼠标移动监听
            document.removeEventListener('mousemove', this.drag);
            // 移除自身，防止内存溢出
            document.removeEventListener('mouseup', this.upPlayer);
        },

        // 播放/暂停 (按钮功能)
        p_s() {
            // 改变按钮样式
            //this.$refs.p_s.classList.toggle('isPlaying');
            if (this.musicList.length > 0) {
                // 如果播放状态
                if (!this.isPlaying) {
                    // 播放音乐
                    this.play();
                }
                // 否则暂停状态
                else {
                    // 暂停音乐
                    this.pause();
                    // 改变信息区状态
                    this.$refs.info.classList.replace('showInfo', 'hiddenInfo');
                }
            } else {
                alert("曲库为空，请先添加音乐！")
            }

        },

        //缓存方法
        //之前尝试了Service Worker,写了之后发现问题太多，所以最终决定放弃采用
        //决定在每次播放之前去查询caches，有则读取，没有再进行请求并缓存
        //参数： 
        //audio->传入audio元素，方便设置src
        //songid->所添加的音乐的id
        async getUrlByCheckCache(audio, songid) {
            //修改加载状态
            this.isLoading = true;
            console.log(songid);
            //打开缓存
            const musicCaches = await caches.open("musicCaches");
            let response;
            //匹配缓存中是否有此id的缓存数据
            let responsePromise = await caches.match(songid);
            if (responsePromise) {
                console.log("有缓存，直接拿");
                response = responsePromise;
            } else {
                console.log("没有缓存，去请求");
                //await fetch(`/API/api/163music?id=${songid}`, { method: 'GET' }).then(data => {
                // (静态部署到PHP虚拟主机时采用)
                await fetch('proxy.php?songid=' + songid, { method: 'GET' }).then(data => {
                    musicCaches.put(songid, data.clone());
                    response = data;
                });
            }
            await response.blob().then(blob => {
                const objectUrl = URL.createObjectURL(blob);
                audio.src = objectUrl;
            }).then(objectUrl => {
                // 清理
                URL.revokeObjectURL(objectUrl);
                console.log("执行完毕");
            });
            //完成加载
            this.isLoading = false;
        },

        // 播放
        async play() {
            //检查是否正在加载
            if(this.isLoading){
                alert("正在加载中...请耐心等待即可");
                return;
            }
            this.isPlaying = true;
            // 如果src为空，就去请求并赋予
            if (!this.$refs.player.currentSrc || this.$refs.player.src == '')
                await this.getUrlByCheckCache(this.$refs.player, this.musicList[this.playingMusic]?.songid);
            // 捕获一下异常
            try {
                await this.$refs.player.play();
            } catch (err) {
                if (err.name == 'AbortError')
                    return;
                // 回退播放状态（不然小bug）
                this.isPlaying = false;
                alert("出现了问题，不可播放！错误信息：\n " + err + '\n请检查该歌曲是否为收费歌曲，为保护版权，请支持正版');
                return;
            }
            this.$refs.p_s.classList.add('isPlaying');
            this.$refs.smallView.classList.add('sviewIsPlaying');

            // 添加海报旋转样式
            this.$refs.posters.children[0].classList.add('rotateImg');
            this.$refs.smallView.children[0].classList.add('rotateImg');

            // 旋转海报
            this.$refs.posters.children[0].style.animationPlayState = 'running';
            this.$refs.smallView.children[0].style.animationPlayState = 'running';

            // 判断改变信息区状态
            if (this.$refs.info.classList.contains("hiddenInfo")) {
                this.$refs.info.classList.replace('hiddenInfo', 'showInfo');
            } else {
                this.$refs.info.classList.add('showInfo');
            }

            // 修改曲库当前播放歌曲的样式
            [...this.$refs.music.children].forEach(item => {
                item.style.color = 'black';
            });
            this.$refs.music.children[this.playingMusic].style.color = 'red';

            // 标题滚动(已废弃，直接采用固定值-50% - 50%)
            //const textWidth = this.$refs.title.scrollWidth;
            //this.$refs.info.style.setProperty("--textWidth", -textWidth + "rem");
            // 处理歌词
            if (this.musicList[this.playingMusic].lyrics == null || this.musicList[this.playingMusic].lyricsTime == null) {
                var timeArr = [];
                let lrcArr = [];
                const str = this.musicList[this.playingMusic].lrc.split('\n');
                str.forEach(item => {
                    const splitLyc = item.split(']');
                    //console.log(splitLyc);
                    timeArr.push(this.timeFormat(splitLyc[0].substr(1, splitLyc[0].length)));
                    lrcArr.push(splitLyc[1]);
                })
                //console.log(timeArr);
                //console.log(lrcArr);
                this.musicList[this.playingMusic].lyrics = lrcArr;
                this.musicList[this.playingMusic].lyricsTime = timeArr;
            }

        },
        // 格式化歌词时间（把原歌词字符的时间格式化，例 参数 00:04.129 return 4，代表是第四秒）
        timeFormat(timeStr) {
            if (timeStr) {
                const timeStrArr = timeStr.split(':')
                //console.log(timeStrArr);
                const minute = timeStrArr[0][0] == '0' ? timeStrArr[0][1] : timeStrArr[0]
                const second = timeStrArr[1][0] == '0' ? timeStrArr[1][1] : timeStrArr[1]
                return parseInt(minute) * 60 + parseInt(second)
            }
        },

        // 暂停
        async pause() {
            this.isPlaying = false;
            await this.$refs.player.pause();
            this.$refs.p_s.classList.remove('isPlaying');
            this.$refs.smallView.classList.remove('sviewIsPlaying');
            // 暂停旋转海报
            this.$refs.posters.children[0].style.animationPlayState = 'paused';
            this.$refs.smallView.children[0].style.animationPlayState = 'paused';
        },
        // 下一首
        async next() {
            // 改变信息区状态
            this.$refs.info.classList.replace('showInfo', 'hiddenInfo');
            await this.pause();
            if (this.musicList.length > 0) {
                this.progress = 0;
                // 替换源（直接数组下标下一个）
                this.playingMusic++;
                // 判断是否是最后一首
                if (this.playingMusic > this.musicList.length - 1) {
                    this.playingMusic = 0;
                }
                //获取这首歌的资源
                this.getUrlByCheckCache(this.$refs.player, this.musicList[this.playingMusic]?.songid);
                // 监听，当准备就绪，播放
                this.$refs.player.oncanplay = () => {
                    this.play();
                    // 去除监听，防止拖动进度条滑块时自动播放
                    this.$refs.player.oncanplay = null;
                }
            } else {
                alert("曲库为空，请先添加音乐！");
            }
        },
        // 上一首，同理
        async last() {
            // 改变信息区状态
            this.$refs.info.classList.replace('showInfo', 'hiddenInfo');
            await this.pause();
            if (this.musicList.length > 0) {
                this.progress = 0;
                this.playingMusic--;
                if (this.playingMusic < 0) {
                    this.playingMusic = this.musicList.length - 1;
                }
                //获取这首歌的资源
                this.getUrlByCheckCache(this.$refs.player, this.musicList[this.playingMusic]?.songid);
                this.$refs.player.oncanplay = () => {
                    this.play();
                    this.$refs.player.oncanplay = null;
                }
            } else {
                alert("曲库为空，请先添加音乐！");
            }
        },
        // 播放完了直接下一首
        ended() {
            this.next();
        },

        // 鼠标按下监听 用于 按下音乐进度条滑块时暂停
        mousedown() {
            if (!this.$refs.player.paused)
                this.pause();
        },
        // 鼠标松开监听 用于 松开音乐进度条滑块时继续播放
        mouseup() {
            if (this.$refs.player.buffered.length > 0 && this.$refs.player.paused)
                this.play();
        },

        // input监听 用于 拖动音乐进度条 改变进度值
        updateProgress(e) {
            let duration = this.$refs.player.duration;
            let buffered = this.$refs.player.buffered;
            if (buffered.length > 0 && !isNaN(duration) && duration > 0) {
                //console.log("已经开始加载了");
                //感觉没必要
                // let time = e.target.value * duration;
                // if (() => {
                //     for (let i = 0; i < buffered.length; i++) {
                //         const start = buffered.start(i);
                //         const end = buffered.end(i);
                //         if (time >= start && time <= end)
                //             return true;
                //     }
                //     return false;
                // }) {

                // } else {
                //     console.log("还没有加载这里");
                //     this.$refs.player.addRange(time, duration);
                // }
                this.progress = e.target.value;
                this.$refs.player.currentTime = this.progress / 100 * this.$refs.player.duration;
            } else {
                //console.log("根本没开始加载");
                e.target.value = 0;
            }
        },

        // audio 的 timeupdate监听（每500ms更新一次） 用于 跟踪监听音乐进度
        updateProgressBar() {
            //console.log(this.$refs.player.currentTime);
            //console.log(this.$refs.player.duration);
            //console.log(this.progress);
            // 播放进度
            this.progress = this.$refs.player.currentTime / this.$refs.player.duration * 100;
            // 已播放时长
            this.currentTime = this.formatTime(this.$refs.player.currentTime);
            // 总时长
            this.duration = this.formatTime(this.$refs.player.duration);

            let musicList = this.musicList;
            if (musicList && this.musicList[this.playingMusic]?.lyricsTime != null) {
                //歌词
                //当前秒数（向下取整）
                var nowSecond = Math.floor(this.$refs.player.currentTime);
                //console.log('nowSecond:'+nowSecond);
                //查询对应时间的下标
                //(reduce方法，将需要查询的数与cur比较，不是则返回-1，是则返回该数在此数组的下标)
                const index = musicList[this.playingMusic].lyricsTime.reduce((acc, cur, i) => {
                    if (cur === nowSecond) acc = i;
                    return acc;
                }, -1);

                //console.log(index);
                if (index != -1) {
                    // (废弃)
                    // 移除所有歌词的效果
                    // [...this.$refs.lyric.children].forEach(item => {
                    //     item.classList.remove('active');
                    // })
                    // 给当前歌词添加效果class
                    //this.$refs.lyric.children[index].classList.add('active');
                    
                    //（滚动歌词）
                    // 因为是滚动歌词,所以滚动的距离就是整个歌词元素的上升距离,等于第几句-1(等于下标) * 每句需要移动的距离
                    this.$refs.lyric.style.top = index * -40 + 'rem';
                }
            }


            // 保持与audio组件同步（可能会浪费性能，取而代之的是加两个监听器，播放、暂停监听器）
            // if(this.$refs.player.paused){
            //     this.pause();
            // }else{
            //     this.play();
            // }

        },

        // 格式化时间（进度条时间，总秒数 变 分：秒）
        formatTime(time) {
            if (isNaN(time)) {
                return '00:00';
            }
            // 将time分解成分钟和秒
            let minute = Math.floor(time / 60);
            let second = Math.floor(time % 60);

            // 添加前导零,
            second = second < 10 ? '0' + second : second;
            minute = minute < 10 ? '0' + minute : minute;

            // 拼接成mm:ss格式    
            return minute + ':' + second;
        },

        // 播放监听 用于 保持UI与audio的同步
        // (bug修复)注意添加if判断，否则每次点击播放暂停后都会被监听调用， 
        //导致播放、暂停方法被连续调用两次
        playerPlay() {
            if (!this.isPlaying)
                this.play();
        },

        // 暂停监听 用于 保持UI与audio的同步
        playerPause() {
            if (this.isPlaying)
                this.pause();
        },

        // 以下三个监听 用于 调整音量大小
        // 音量，鼠标按下监听
        mousedownVolume(e) {
            this.$refs.posters.addEventListener('mousemove', this.mousemoveVolume);
            document.addEventListener('mouseup', this.setVolume);
        },
        // 音量，鼠标移动监听
        mousemoveVolume(e) {
            const volumeDiv = e.currentTarget;  // 音量控制div   
            const volumeHeight = volumeDiv.clientHeight;  // 音量控制器高度 
            //console.log(volumeDiv.getBoundingClientRect().top);
            //console.log(volumeDiv.getBoundingClientRect().top + volumeDiv.clientHeight);
            //console.log(e.pageY);
            const clickY = e.pageY - volumeDiv.getBoundingClientRect().top;
            let height = 1 - clickY / volumeHeight;  // 计算高度
            this.$refs.posters.style.setProperty("--volumeHeight", (height * 100) + '%');
        },
        // 设置音量，鼠标松开监听
        setVolume(e) {
            this.$refs.posters.removeEventListener('mousemove', this.mousemoveVolume);
            const volumeDiv = this.$refs.posters;  // 音量控制div   
            const volumeHeight = volumeDiv.clientHeight;  // 音量控制器高度 
            //console.log(volumeHeight);
            //console.log(e.pageY);
            //console.log(volumeDiv.getBoundingClientRect().top);
            let volume = 0;
            if (e.pageY > volumeDiv.getBoundingClientRect().top + volumeDiv.clientHeight) {
                volume = 0;
            } else if (e.pageY < volumeDiv.getBoundingClientRect().top) {
                volume = 1;
            } else {
                const clickY = e.pageY - volumeDiv.getBoundingClientRect().top;  // 相对音量控制器顶部的 Y 坐标
                //console.log(clickY);
                volume = 1 - clickY / volumeHeight;  // 计算音量       
            }
            //console.log(volume);
            // setVolume 范围 0-1
            this.volume = volume;
            this.$refs.player.volume = this.volume;
            this.$refs.posters.style.setProperty("--volumeHeight", (volume * 100) + '%');
            document.removeEventListener('mouseup', this.setVolume);

        },
        // 音量变化监听 用于同步audio音量发生改变时同步样式（虽然测试完成后会关闭原生audio控制台）
        volumechange(e) {
            this.$refs.posters.style.setProperty("--volumeHeight", e.target.volume * 100 + '%');
        },

        // 展开、关闭曲库界面
        library() {
            const library = this.$refs.library;
            library.style.height = library.style.height === '300rem' ? '0' : '300rem';
            library.style.opacity = library.style.opacity === '1' ? '0' : '1';
        },

        // 添加音乐
        addMusic() {
            let musicName = prompt("歌名");
            if (musicName == null) {
                return;
            } else {
                // (静态部署到PHP虚拟主机时采用)
                fetch('proxy.php?url=http://myfreemp3.sharerj.com', {
                //fetch('/myfreemp3', {
                    method: 'post',
                    headers: {
                        'Accept': 'application/json, text/javascript, */*; q=0.01',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.183',
                        'X-Requested-With': 'XMLHttpRequest',
                        'Connection': 'keep-alive',
                    },
                    body: 'input=' + musicName + '&filter=name&type=netease&page=1',
                    mode: 'cors',
                })
                    .then(response => {
                        return response.json();
                    })
                    .then(data => {
                        let responseData = data.data[0];
                        this.musicList.push(responseData);
                        let musicList = JSON.stringify(this.musicList);
                        localStorage.setItem("musicList", musicList);
                        console.log("更新了音乐曲库", JSON.parse(musicList));
                    })
                    .catch(err => {
                        console.log(err);
                    })
            }
        },

        // 删除曲库歌曲
        deleteMusic(index) {
            this.pause();
            this.$refs.info.classList.replace('showInfo', 'hiddenInfo');
            if (this.playingMusic > 0)
                this.last();
            else
                this.$refs.player.removeAttribute('src');
            this.musicList.splice(index, 1);
            console.log("删除成功", this.musicList);
            // 更新本地缓存
            let musicList = JSON.stringify(this.musicList);
            localStorage.setItem("musicList", musicList);
        },

        // 曲库点击切歌
        async checkPlay(index) {
            // 改变信息区状态
            this.$refs.info.classList.replace('showInfo', 'hiddenInfo');
            await this.pause();
            // 替换源（直接数组下标下一个）
            this.playingMusic = index;
            //获取这首歌的资源
            this.getUrlByCheckCache(this.$refs.player, this.musicList[this.playingMusic]?.songid);
            // 监听，当准备就绪，播放
            this.$refs.player.oncanplay = () => {
                this.play();
                // 去除监听，防止拖动进度条滑块时自动播放
                this.$refs.player.oncanplay = null;
            }
        },


    },
}
</script>

